package org.jeecg.modules.materialUsage.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.inventory.entity.Inventory;
import org.jeecg.modules.inventory.service.IInventoryService;
import org.jeecg.modules.inventoryDetail.entity.InventoryDetail;
import org.jeecg.modules.inventoryDetail.service.IInventoryDetailService;
import org.jeecg.modules.materialUsage.entity.MaterialUsage;
import org.jeecg.modules.materialUsage.service.IMaterialUsageService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 出库信息表
 * @Author: jeecg-boot
 * @Date:   2025-04-15
 * @Version: V1.0
 */
@Api(tags="出库信息表")
@RestController
@RequestMapping("/materialUsage/materialUsage")
@Slf4j
public class MaterialUsageController extends JeecgController<MaterialUsage, IMaterialUsageService> {
	@Autowired
	private IMaterialUsageService materialUsageService;
	@Autowired
	private IInventoryService inventoryService;
	@Autowired
	private IInventoryDetailService inventoryDetailService;
	
	/**
	 * 分页列表查询
	 *
	 * @param materialUsage
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "出库信息表-分页列表查询")
	@ApiOperation(value="出库信息表-分页列表查询", notes="出库信息表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(MaterialUsage materialUsage,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<MaterialUsage> queryWrapper = QueryGenerator.initQueryWrapper(materialUsage, req.getParameterMap());
		Page<MaterialUsage> page = new Page<MaterialUsage>(pageNo, pageSize);
		IPage<MaterialUsage> pageList = materialUsageService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

     // 新增常量类
     public interface InventoryStatus {
         int NORMAL = 1;
         int PARTIAL_OUT = 2;
         int FULL_OUT = 3;
     }
     
     public interface MaterialUsageStatus {
         int OUT_SUCCESS = 2;
     }
     
     @AutoLog(value = "出库信息表-确认出库")
     @ApiOperation(value="出库信息表-确认出库", notes="出库信息表-确认出库")
     @PostMapping(value = "/out")
     @Transactional(rollbackFor = Exception.class) // 添加事务注解
     public Result<?> out(@RequestBody MaterialUsage materialUsage) {
         try {
             String batchId = materialUsage.getBatchId();
             // 添加行级锁查询
             Inventory byBatchId = inventoryService.getByBatchId(batchId);
             
             if (byBatchId == null) {
                 log.warn("库存不存在，批次ID: {}", batchId);
                 return Result.error("未找到对应数据");
             }
     
             BigDecimal requestQty = materialUsage.getQuantity();
             if (byBatchId.getCurrentQuantity().compareTo(requestQty) < 0) {
                 log.warn("库存不足，批次ID: {}，当前库存: {}，请求数量: {}", 
                     batchId, byBatchId.getCurrentQuantity(), requestQty);
                 return Result.error("当前库存不足");
             }

			 if (byBatchId.getStatus() == InventoryStatus.FULL_OUT) {
                 log.warn("库存已全部出库，批次ID: {}", batchId);
                 return Result.error("库存已全部出库");
             }

			 BigDecimal remainingQty = requestQty; // 剩余需要扣减的数量
			 List<InventoryDetail> detailsToUpdate = new ArrayList<>();

			// 按创建时间升序排列（先进先出）
			 List<InventoryDetail> byInventoryId = inventoryDetailService.getByInventoryIdOrderByCreateTimeAsc(byBatchId.getId());

			 for (InventoryDetail inventoryDetail : byInventoryId) {
				 if (remainingQty.compareTo(BigDecimal.ZERO) <= 0) break;

				 BigDecimal available = inventoryDetail.getCurrentQuantity();
				 // 实际扣减量取两者较小值
				 BigDecimal deduct = available.min(remainingQty);

				 inventoryDetail.setCurrentQuantity(available.subtract(deduct));
				 detailsToUpdate.add(inventoryDetail);
				 remainingQty = remainingQty.subtract(deduct);
			 }

			// 批量更新明细（需要确保remainingQty最终为0）
			 if (remainingQty.compareTo(BigDecimal.ZERO) != 0) {
				 log.error("库存明细扣减异常，批次ID: {}，剩余未扣减量: {}", batchId, remainingQty);
				 throw new RuntimeException("库存扣减异常");
			 }

			// 更新库存明细
			 if (!inventoryDetailService.updateBatchById(detailsToUpdate)) {
				 log.error("库存明细更新失败，批次ID: {}", batchId);
				 throw new RuntimeException("库存明细更新失败");
			 }

			 // 扣减库存
             BigDecimal newQuantity = byBatchId.getCurrentQuantity().subtract(requestQty);
             updateInventoryStatus(byBatchId, newQuantity);
             byBatchId.setCurrentQuantity(newQuantity);
             
             if (!inventoryService.updateById(byBatchId)) {
                 log.error("库存更新失败，批次ID: {}", batchId);
                 throw new RuntimeException("库存更新失败");
             }
     
             // 更新领用状态
             materialUsage.setStatus(MaterialUsageStatus.OUT_SUCCESS);
			 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			 materialUsage.setOperator(user.getRealname());
             if (!materialUsageService.updateById(materialUsage)) {
                 log.error("领用记录更新失败，ID: {}", materialUsage.getId());
                 throw new RuntimeException("领用记录更新失败");
             }
     
             return Result.OK("出库成功！");
         } catch (Exception e) {
             log.error("出库操作异常，批次ID: {}，异常信息: {}", 
                 materialUsage.getBatchId(), e.getMessage(), e);
             throw new RuntimeException("出库操作失败，请稍后重试");
         }
     }
     
     // 提取状态设置方法
     private void updateInventoryStatus(Inventory inventory, BigDecimal newQuantity) {
         if (newQuantity.compareTo(BigDecimal.ZERO) > 0) {
             inventory.setStatus(InventoryStatus.PARTIAL_OUT);
         } else {
             inventory.setStatus(InventoryStatus.FULL_OUT);
         }
     }
	
	/**
	 *   添加
	 *
	 * @param materialUsage
	 * @return
	 */
	@AutoLog(value = "出库信息表-添加")
	@ApiOperation(value="出库信息表-添加", notes="出库信息表-添加")
	@PostMapping(value = "/add")
	@Transactional(rollbackFor = Exception.class) // 添加事务注解
	public Result<?> add(@RequestBody MaterialUsage materialUsage) {
		try {
			Integer materialType = materialUsage.getMaterialType();

			String materialId = materialUsage.getMaterialId();
			String tankId = materialUsage.getTankId();
			BigDecimal requiredQty = materialUsage.getQuantity();

			// 1. 获取库存列表（按创建时间排序）
			List<Inventory> inventoryList = inventoryService.getByMaterialIdAndTankIdOrderByCreateTime(materialId, tankId);

			// 2. 计算总库存
			BigDecimal totalStock = inventoryList.stream()
					.map(Inventory::getCurrentQuantity)
					.reduce(BigDecimal.ZERO, BigDecimal::add);

			// 3. 库存不足判断
			if (totalStock.compareTo(requiredQty) < 0) {
				log.warn("库存不足，需求数量: {}，总库存: {}", requiredQty, totalStock);
				return Result.error("库存不足");
			}

			// 4. 分配库存
			List<MaterialUsage> saveList = new ArrayList<>();
			BigDecimal remainingQty = requiredQty;

			for (Inventory inventory : inventoryList) {
				if (remainingQty.compareTo(BigDecimal.ZERO) <= 0) break;

				MaterialUsage saveUsage = new MaterialUsage();
				BigDecimal allocatedQty = inventory.getCurrentQuantity().min(remainingQty);

				// 设置出库记录
				saveUsage.setBatchId(inventory.getBatchId())
						.setPurpose(materialUsage.getPurpose())
						.setTankId(inventory.getTankId())
						.setQuantity(allocatedQty)
						.setUsageTime(materialUsage.getUsageTime())
						.setOperator(materialUsage.getOperator())
						.setMaterialId(materialId)
						.setMaterialType(materialUsage.getMaterialType())
						.setStatus(1);

				saveList.add(saveUsage);
				remainingQty = remainingQty.subtract(allocatedQty);
			}

			// 5. 批量保存出库记录
			if (!materialUsageService.saveBatch(saveList)) {
				log.error("出库记录保存失败");
				throw new RuntimeException("出库操作失败");
			}

			return Result.OK("添加成功！");
		} catch (Exception e) {
			log.error("添加领用记录异常，物料ID: {}，异常信息: {}",
					materialUsage.getMaterialId(), e.getMessage(), e);
			return Result.error("操作失败，请稍后重试");
		}
	}


	 /**
	 *  编辑
	 *
	 * @param materialUsage
	 * @return
	 */
	@AutoLog(value = "出库信息表-编辑")
	@ApiOperation(value="出库信息表-编辑", notes="出库信息表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody MaterialUsage materialUsage) {
		materialUsageService.updateById(materialUsage);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "出库信息表-通过id删除")
	@ApiOperation(value="出库信息表-通过id删除", notes="出库信息表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		materialUsageService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "出库信息表-批量删除")
	@ApiOperation(value="出库信息表-批量删除", notes="出库信息表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.materialUsageService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "出库信息表-通过id查询")
	@ApiOperation(value="出库信息表-通过id查询", notes="出库信息表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		MaterialUsage materialUsage = materialUsageService.getById(id);
		if(materialUsage==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(materialUsage);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param materialUsage
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MaterialUsage materialUsage) {
        return super.exportXls(request, materialUsage, MaterialUsage.class, "出库信息表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MaterialUsage.class);
    }

}
